<template>
  <div class="restaurant-manage">
    <div class="page-header">
      <div class="header-title">餐厅管理</div>
      <div class="header-actions">
        <el-button type="primary" icon="el-icon-plus" @click="handleAddRestaurant">添加餐厅</el-button>
      </div>
    </div>

    <div class="search-bar">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="餐厅名称">
          <el-input v-model="searchForm.keyword" placeholder="输入餐厅名称"></el-input>
        </el-form-item>
        <el-form-item label="餐厅分类">
          <el-select v-model="searchForm.category" placeholder="请选择" clearable>
            <el-option
              v-for="item in categoryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择" clearable>
            <el-option label="营业中" :value="1"></el-option>
            <el-option label="已关闭" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table
      :data="restaurantList"
      border
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="name" label="餐厅名称" min-width="150"></el-table-column>
      <el-table-column prop="category" label="分类" width="120"></el-table-column>
      <el-table-column prop="address" label="地址" min-width="200"></el-table-column>
      <el-table-column prop="phone" label="联系电话" width="150"></el-table-column>
      <el-table-column prop="rating" label="评分" width="100">
        <template slot-scope="scope">
          {{ scope.row.rating }} <i class="el-icon-star-on" style="color: #FF9900;"></i>
        </template>
      </el-table-column>
      <el-table-column prop="monthlySales" label="月销量" width="100"></el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEditRestaurant(scope.row)">编辑</el-button>
          <el-button size="mini" type="success" @click="handleManageDish(scope.row)">菜品管理</el-button>
          <el-button size="mini" type="danger" @click="handleDeleteRestaurant(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size="pageSize"
        :current-page.sync="currentPage"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange">
      </el-pagination>
    </div>

    <!-- 餐厅表单对话框 -->
    <el-dialog 
      :title="dialogType === 'add' ? '添加餐厅' : '编辑餐厅'" 
      :visible.sync="dialogVisible"
      width="600px"
    >
      <el-form :model="restaurantForm" :rules="rules" ref="restaurantForm" label-width="100px">
        <el-form-item label="餐厅名称" prop="name">
          <el-input v-model="restaurantForm.name"></el-input>
        </el-form-item>
        <el-form-item label="餐厅分类" prop="category">
          <el-select v-model="restaurantForm.category" placeholder="请选择" style="width: 100%;">
            <el-option
              v-for="item in categoryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="餐厅地址" prop="address">
          <el-input v-model="restaurantForm.address"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="restaurantForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="餐厅图片" prop="image">
          <el-input v-model="restaurantForm.image" placeholder="图片URL"></el-input>
        </el-form-item>
        <el-form-item label="营业时间" prop="businessHours">
          <el-input v-model="restaurantForm.businessHours" placeholder="例如: 10:00-22:00"></el-input>
        </el-form-item>
        <el-form-item label="配送费" prop="deliveryFee">
          <el-input-number v-model="restaurantForm.deliveryFee" :min="0" :precision="2" :step="0.5"></el-input-number>
        </el-form-item>
        <el-form-item label="起送价" prop="minOrderAmount">
          <el-input-number v-model="restaurantForm.minOrderAmount" :min="0" :precision="2" :step="5"></el-input-number>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="restaurantForm.status">
            <el-radio :label="1">营业中</el-radio>
            <el-radio :label="0">已关闭</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="餐厅介绍" prop="description">
          <el-input type="textarea" v-model="restaurantForm.description" :rows="4"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitRestaurantForm" :loading="submitting">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'RestaurantManage',
  data() {
    return {
      loading: false,
      submitting: false,
      restaurantList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      searchForm: {
        keyword: '',
        category: '',
        status: ''
      },
      categoryOptions: [
        { value: '川菜', label: '川菜' },
        { value: '粤菜', label: '粤菜' },
        { value: '烧烤', label: '烧烤' },
        { value: '日料', label: '日料' },
        { value: '西餐', label: '西餐' },
        { value: '快餐', label: '快餐' }
      ],
      dialogVisible: false,
      dialogType: 'add', // 'add' or 'edit'
      restaurantForm: {
        id: '',
        name: '',
        category: '',
        address: '',
        phone: '',
        image: 'https://img.yzcdn.cn/vant/cat.jpeg', // 默认图片
        businessHours: '10:00-22:00',
        deliveryFee: 5,
        minOrderAmount: 20,
        status: 1,
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入餐厅名称', trigger: 'blur' }
        ],
        category: [
          { required: true, message: '请选择餐厅分类', trigger: 'change' }
        ],
        address: [
          { required: true, message: '请输入餐厅地址', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$|^0\d{2,3}-\d{7,8}$/, message: '请输入正确的电话号码', trigger: 'blur' }
        ],
        businessHours: [
          { required: true, message: '请输入营业时间', trigger: 'blur' }
        ],
        deliveryFee: [
          { required: true, message: '请输入配送费', trigger: 'blur' }
        ],
        minOrderAmount: [
          { required: true, message: '请输入起送价', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchRestaurantList()
  },
  methods: {
    fetchRestaurantList() {
      this.loading = true
      
      const params = {
        page: this.currentPage,
        size: this.pageSize,
        keyword: this.searchForm.keyword,
        category: this.searchForm.category,
        status: this.searchForm.status
      }
      
      this.$http.get('/admin/restaurant/list', { params })
        .then(response => {
          const { data } = response.data
          this.restaurantList = data.records
          this.total = data.total
        })
        .catch(error => {
          this.$message.error('获取餐厅列表失败')
          console.error('获取餐厅列表失败', error)
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleSearch() {
      this.currentPage = 1
      this.fetchRestaurantList()
    },
    resetSearch() {
      this.searchForm = {
        keyword: '',
        category: '',
        status: ''
      }
      this.handleSearch()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchRestaurantList()
    },
    handleCurrentChange() {
      this.fetchRestaurantList()
    },
    handleAddRestaurant() {
      this.dialogType = 'add'
      this.restaurantForm = {
        id: '',
        name: '',
        category: '',
        address: '',
        phone: '',
        image: 'https://img.yzcdn.cn/vant/cat.jpeg',
        businessHours: '10:00-22:00',
        deliveryFee: 5,
        minOrderAmount: 20,
        status: 1,
        description: ''
      }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.restaurantForm && this.$refs.restaurantForm.clearValidate()
      })
    },
    handleEditRestaurant(row) {
      this.dialogType = 'edit'
      this.restaurantForm = { ...row }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.restaurantForm && this.$refs.restaurantForm.clearValidate()
      })
    },
    handleDeleteRestaurant(row) {
      this.$confirm('确认删除该餐厅？此操作不可恢复', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete(`/admin/restaurant/${row.id}`)
          .then(() => {
            this.$message.success('删除成功')
            this.fetchRestaurantList()
          })
          .catch(error => {
            this.$message.error((error.response && error.response.data && error.response.data.message) || '删除失败')
          })
      }).catch(() => {})
    },
    handleManageDish(row) {
      this.$router.push({
        path: '/admin/dish',
        query: { restaurantId: row.id }
      })
    },
    handleStatusChange(row) {
      this.$http.put(`/admin/restaurant/${row.id}/status`, null, {
        params: { status: row.status }
      })
        .then(() => {
          this.$message.success(`餐厅状态已${row.status === 1 ? '开启' : '关闭'}`)
        })
        .catch(error => {
          // 恢复状态
          row.status = row.status === 1 ? 0 : 1
          this.$message.error((error.response && error.response.data && error.response.data.message) || '更新状态失败')
        })
    },
    submitRestaurantForm() {
      this.$refs.restaurantForm.validate(valid => {
        if (valid) {
          this.submitting = true
          
          const request = this.dialogType === 'add'
            ? this.$http.post('/admin/restaurant', this.restaurantForm)
            : this.$http.put('/admin/restaurant', this.restaurantForm)
          
          request
            .then(() => {
              this.$message.success(this.dialogType === 'add' ? '添加成功' : '更新成功')
              this.dialogVisible = false
              this.fetchRestaurantList()
            })
            .catch(error => {
              this.$message.error((error.response && error.response.data && error.response.data.message) || (this.dialogType === 'add' ? '添加失败' : '更新失败'))
            })
            .finally(() => {
              this.submitting = false
            })
        }
      })
    }
  }
}
</script>

<style scoped>
.restaurant-manage {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-title {
  font-size: 20px;
  font-weight: bold;
}

.search-bar {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination-container {
  margin-top: 20px;
  text-align: center;
}
</style>
